package org.csu.softwaremetrics_demo.entity.result.impl;

import org.csu.softwaremetrics_demo.entity.common.LKMetricSingleClass;
import org.csu.softwaremetrics_demo.entity.common.TraditionMetricSingleClass;
import org.csu.softwaremetrics_demo.entity.result.Result;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 传统度量结果类，用于存储和操作所有类的TraditionMetricSingleClass对象。
 * @Author: Jukomu
 * @Package: org.csu.softwaremetrics_demo.entity.result
 * @Project: SoftwareMetrics_demo
 * @name: CKMetricResult
 * @Date: 2025/4/6-20:15
 * @Filename: CKMetricResult
 */
public class TraditionMetricResult implements Result<TraditionMetricSingleClass> {
    private final Map<String, TraditionMetricSingleClass> results;

    public TraditionMetricResult() {
        this.results = new HashMap<>();
    }

    public TraditionMetricResult(Map<String, TraditionMetricSingleClass> results) {
        this.results = results;
    }

    @Override
    public void add(TraditionMetricSingleClass obj) {
        results.put(obj.getFile(), obj);
    }

    @Override
    public TraditionMetricSingleClass get(String name) {
        return results.get(name);
    }

    @Override
    public Collection<TraditionMetricSingleClass> all() {
        return results.values();
    }

    @Override
    public TraditionMetricSingleClass getByClassName(String name) {
        for (TraditionMetricSingleClass singleMetric : results.values()) {
            if (singleMetric.getClassName().equals(name)) {
                return singleMetric;
            }
        }
        return null;
    }

    /**
     * 批量添加度量结果
     * @param metrics 要添加的度量结果列表
     */
    public void setMetrics(Collection<TraditionMetricSingleClass> metrics) {
        if (metrics == null) {
            return;
        }
        metrics.forEach(this::add);
    }

    /**
     * 计算所有类的注释百分比
     */
    public void calculateCp() {
        for (TraditionMetricSingleClass singleMetric : results.values()) {
            double cp = (double) singleMetric.getLenOfComment() / singleMetric.getLoc();
            DecimalFormat df = new DecimalFormat("#.00"); // 格式化字符串，表示两位小数
            // 设置格式化器
            df.setRoundingMode(RoundingMode.HALF_UP); // 设置四舍五入模式
            singleMetric.setCp(Double.parseDouble(df.format(cp)));
        }
    }
}
